package filego

import (
	"fmt"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/go-resty/resty/v2"
)

// Send 当发送文件的时候使用这个函数, 传入文件路径
func (f *File) Send(filepath string) error{
	if f.s == nil {
		f.s = resty.New()
	}
	file,err := os.Open(filepath)
	if err!= nil {
		return err
	}
	defer file.Close()
	resp, err := f.s.R().SetFileReader("file", file.Name(), file).
		SetFormData(map[string]string{
			"pass": f.pass,
		}).
		Post("http://" + f.ip + ":" + f.port + "/upload")
	if err != nil {
		return err
	}
	if resp.StatusCode() != 200 {
		return err
	}
	fmt.Println(resp.String())
	return nil
}

// Run 启动文件传输服务
func (f *File) Run() {
	f.c = gin.Default()
	if(f.ip!="0.0.0.0"){
		f.c.SetTrustedProxies([]string{"http://" + f.ip})
	}
	f.c.POST("/upload", func(c *gin.Context) {
		pass := c.PostForm("pass")
		if pass != f.pass {
			c.String(200, "wrong password错误密码")
			return
		}
		file, err := c.FormFile("file")
		if err != nil {
			c.String(200, "Failed to get file获取文件失败")
			return
		}
		if(f.path[len(f.path)-1] != '/') {
			f.path += "/"
		}
		savepath := f.path+file.Filename
		err = c.SaveUploadedFile(file, savepath)
		if err != nil {
			c.String(200, "Failed to save file保存文件失败")
			return
		}
		c.String(200, "File uploaded successfully文件上传成功")
	}) 
	f.c.Run(":" + f.port)
}


